import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { config } from 'dotenv';
import { User } from '../users/entities/user.entity';
import { Device } from '../devices/entities/device.entity';
import { DeviceAuditCode } from '../device-audit/entities/device-audit-code.entity';
import { Task } from '../tasks/entities/task.entity';
import { TaskTemplate } from '../tasks/entities/task-template.entity';
import { TaskCategory } from '../tasks/entities/task-category.entity';
import { Content } from '../contents/entities/content.entity';
import { Tag } from '../tags/entities/tag.entity';
import { Attachment } from '../contents/entities/attachment.entity';
import { ContentTagMapping } from '../tags/entities/content-tag-mapping.entity';

// Load environment variables
config();
const configService = new ConfigService();

// Determine if we're in production mode
const isProd = configService.get('NODE_ENV') === 'production';

const dataSource = new DataSource({
  type: 'postgres',
  host: configService.get('DB_HOST'),
  port: parseInt(configService.get('DB_PORT') || '5432'),
  username: configService.get('DB_USERNAME'),
  password: configService.get('DB_PASSWORD'),
  database: configService.get('DB_DATABASE') || 'api_webservice',
  entities: [
    User,
    Device,
    DeviceAuditCode,
    Task,
    TaskTemplate,
    TaskCategory,
    Content,
    Tag,
    Attachment,
    ContentTagMapping,
  ],
  // Use .js extension in production, .ts in development
  migrations: [isProd ? 'dist/src/migrations/*.js' : 'src/migrations/*.ts'],
  // Important: synchronize should be false for migrations
  synchronize: false,
});

export default dataSource;
